import React, {Component, createRef, RefObject} from 'react'
import {Button, Card, Form, message, Spin} from 'antd'
import {FormInstance} from 'antd/lib/form'
import wangeditor from 'wangeditor'
import {Store, ValidateErrorEntity} from 'rc-field-form/lib/interface'
import {contactUsReq, modifyContactUsReq} from '../../../../requests/contactUs'
import {getRes} from "../../../../configFile";


interface IProps { }
interface IState {
    isLoading: boolean
    contactWayContent: string
    siteProfileContent: string
}
export default class ModifyAboutUs extends Component<IProps, IState> {
    // 编辑器引用
    contactWayRef: RefObject<HTMLDivElement> = createRef()
    siteProfileRef: RefObject<HTMLDivElement> = createRef()
    //创建Form引用  
    formRef = React.createRef<FormInstance>()
    //初始化富文本编辑器
    //编辑器实例声明 再didmount后操作DOM
    contactWayEditor: any
    siteProfileEditor: any

    constructor(props: IProps) {
        super(props)
        this.state = {
            contactWayContent: '',
            siteProfileContent: '',
            isLoading: true
        }
    }

    //提交失败
    onFinishFailed = (errorInfo: ValidateErrorEntity) => {
        message.error(errorInfo.errorFields[0].errors[0]);
    };

    //提交成功
    onFinish: (values: Store) => void = async values => {
        console.log(values);
        this.setState({
            ...this.state,
            isLoading: true
        })
        try {
            const res = getRes(await modifyContactUsReq(values.contactWay, values.siteProfile))
            console.log(res);
            if (res.isSuccessful === true) {
                message.success("修改成功")
            } else {
                message.error("修改失败")
            }
        } catch (err) {
            message.error(JSON.stringify(err))
        } finally {
            this.setState({
                ...this.state,
                isLoading: false
            })
        }
    }


    //初始化编辑器
    initEditor = () => {
        this.contactWayEditor = new wangeditor(this.contactWayRef.current)
        this.contactWayEditor.customConfig.zIndex = 100
        this.contactWayEditor.customConfig.onchange = (htmlContent: string) => {
            if (this.formRef.current)
                this.formRef.current.setFieldsValue({ 'contactWay': htmlContent })
            else
                console.log('不存在引用');
        }
        // this.contactWayEditor.customConfig.uploadImgShowBase64 = true   // 使用 base64 保存图片   数据库不允许过长
        this.contactWayEditor.create()

        this.siteProfileEditor = new wangeditor(this.siteProfileRef.current)
        this.siteProfileEditor.customConfig.zIndex = 100
        this.siteProfileEditor.customConfig.onchange = (htmlContent: string) => {
            if (this.formRef.current)
                this.formRef.current.setFieldsValue({ 'siteProfile': htmlContent })
            else
                console.log('不存在引用');

        }
        // this.siteProfileEditor.customConfig.uploadImgShowBase64 = true   // 使用 base64 保存图片
        this.siteProfileEditor.create()
    }

    componentDidMount = async () => {
        this.initEditor()       //操作DOM初始化editor
        try {
            const res = getRes(await contactUsReq())
            console.log(res);

            if (res.isSuccessful === true) {
                this.contactWayEditor.txt.html(res.data.contactWay)
                this.siteProfileEditor.txt.html(res.data.siteProfile)
                //设置表单域    实例不为空
                if (this.formRef.current) {
                    console.log(res.data);
                    this.formRef.current.setFieldsValue({ contactWay: res.data.contactWay, siteProfile: res.data.siteProfile })
                    console.log(this.formRef.current.getFieldValue('content'));
                }
                else
                    console.log('didmount不存在引用');

            } else {
                message.error(res.message)
            }
            this.setState({
                ...this.state,
                isLoading: false
            })
        } catch (err) {
            message.error(JSON.stringify(err))
        }
    }
    render() {
        return (
            <div>
                <Spin spinning={this.state.isLoading}>
                    <Card title='修改关于我们'>
                        <Form
                            onFinishFailed={this.onFinishFailed}
                            onFinish={this.onFinish}
                            ref={this.formRef}
                            name="AboutUs"
                            hideRequiredMark
                        >


                            <Form.Item
                                label='联系方式'
                                name="contactWay"
                                rules={[
                                    {
                                        required: true,
                                        message: '联系我们内容必填',
                                    },
                                ]}
                            >
                                <div className="editorDiv" ref={this.contactWayRef} />
                            </Form.Item>

                            <Form.Item
                                name="siteProfile"
                                label='网站简介'
                                rules={[
                                    {
                                        required: true,
                                        message: '网站简介内容必填',
                                    },
                                ]}
                            >
                                <div className="editorDiv" ref={this.siteProfileRef} />
                            </Form.Item>

                            <Form.Item
                            >
                                <Button type="primary" htmlType="submit" size="large">
                                    确认修改
                            </Button>
                            </Form.Item>

                        </Form>
                    </Card>
                </Spin>
            </div>
        )
    }
}
